package top.frsf.autocodegen.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.frsf.autocodegen.controller.dto.AutoDataSourceAddDTO;
import top.frsf.autocodegen.entity.AutoDatasource;
import top.frsf.autocodegen.entity.AutoTable;
import top.frsf.autocodegen.service.IAutoDatasourceService;
import top.frsf.autocodegen.utils.JdbcSessionFactoryUtil;
import top.frsf.autocodegen.utils.Result;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author FRSF
 * @since 2024/7/25 17:13
 */
@Slf4j
@Tag(name = "1 - 数据源管理")
@RestController
@RequestMapping("/autoDatasource")
public class AutoDatasourceController {

    @Resource
    private IAutoDatasourceService autoDataSourceService;

    @GetMapping
    @Operation(summary = "获取所有已添加的数据源")
    public Result<List<AutoDatasource>> getAll() {
        List<AutoDatasource> list = autoDataSourceService.list();
        return Result.success(list);
    }

    @GetMapping("/test/{id}")
    @Operation(summary = "测试数据源连接")
    public Result<Boolean> test(@PathVariable Integer id) {
        AutoDatasource datasource = autoDataSourceService.getDatasourceById(id);
        try {
            try (Connection connection = JdbcSessionFactoryUtil.getSqlSessionFactory(datasource)) {
                return Result.success(true);
            } catch (SQLException e) {
                // 捕获 SQL 异常，给出更具体的错误信息
                log.error("数据库连接失败: {}", e.getMessage());
                return Result.fail("数据库连接失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("连接失败，系统异常", e);
            return Result.fail("连接失败，系统异常");
        }
    }

    @GetMapping("/table/{id}")
    @Operation(summary = "获取指定ID数据源的表集合")
    public Result<List<AutoTable>> listTablesByDatasourceId(@PathVariable Integer id) throws SQLException, ClassNotFoundException {
        List<AutoTable> autoTables = autoDataSourceService.listTableByDatasourceId(id);
        return Result.success(autoTables);
    }

    @PostMapping
    @Operation(summary = "新增数据源")
    public Result<Boolean> save(@Validated @RequestBody AutoDataSourceAddDTO dto) {
        return autoDataSourceService.saveDatasource(dto);
    }

    @DeleteMapping
    @Operation(summary = "删除指定ID数据源")
    public Result<Boolean> delete(@RequestParam Integer id) {
        boolean delete = autoDataSourceService.removeById(id);
        return delete ? Result.success(true) : Result.fail("删除失败");
    }


}
